package com.xdl.modules.system.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xdl.common.constants.CommonConstants;
import com.xdl.common.response.ResponseCollection;
import com.xdl.common.response.ResponseResult;
import com.xdl.common.utils.StringUtils;
import com.xdl.modules.system.entity.SysDepartRolePermission;
import com.xdl.modules.system.entity.SysPermission;
import com.xdl.modules.system.model.TreeModel;
import com.xdl.modules.system.service.SysDepartRolePermissionService;
import com.xdl.modules.system.service.SysPermissionService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门权限表 前端控制器
 * </p>
 *
 * @author iron guo
 * @since 2022-03-08
 */
@Slf4j
@RestController
@RequestMapping("/sys/sysDepartPermission")
public class SysDepartPermissionController {

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private SysDepartRolePermissionService sysDepartRolePermissionService;

    /**
     * 用户角色授权功能，查询菜单权限树
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryTreeListForDeptRole", method = RequestMethod.GET)
    public ResponseResult<Map<String, Object>> queryTreeListForDeptRole(@RequestParam(name = "departId", required = true) String departId) {
        //全部权限ids
        List<String> ids = Lists.newArrayList();
        LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
        query.eq(SysPermission::getDelFlag, CommonConstants.DEL_FLAG_0);
        query.orderByAsc(SysPermission::getSortNo);
        query.inSql(SysPermission::getId, "select permission_id  from sys_depart_permission where depart_id='" + departId + "'");
        List<SysPermission> list = sysPermissionService.list(query);
        for (SysPermission sysPer : list) {
            ids.add(sysPer.getId());
        }
        List<TreeModel> treeList = Lists.newArrayList();
        getTreeModelList(treeList, list, null);
        Map<String, Object> resMap = Maps.newHashMap();
        resMap.put("treeList", treeList); //全部树节点数据
        resMap.put("ids", ids);//全部树ids
        return ResponseResult.Success(resMap);
    }

    /**
     * 查询角色授权
     *
     * @return
     */
    @RequestMapping(value = "/queryDeptRolePermission", method = RequestMethod.GET)
    public ResponseCollection<String> queryDeptRolePermission(@RequestParam(name = "roleId", required = true) String roleId) {
        List<SysDepartRolePermission> list = sysDepartRolePermissionService.list(new QueryWrapper<SysDepartRolePermission>().lambda().eq(SysDepartRolePermission::getRoleId, roleId));
        List<String> result = list.stream().map(SysDepartRolePermission -> String.valueOf(SysDepartRolePermission.getPermissionId())).collect(Collectors.toList());
        return ResponseCollection.Success(result);
    }


    /**
     * 保存角色授权
     *
     * @return
     */
    @RequestMapping(value = "/saveDeptRolePermission", method = RequestMethod.POST)
    public ResponseResult<Boolean> saveDeptRolePermission(@RequestBody JSONObject json) {
        String roleId = json.getString("roleId");
        String permissionIds = json.getString("permissionIds");
        String lastPermissionIds = json.getString("lastpermissionIds");
        boolean save=this.sysDepartRolePermissionService.saveDeptRolePermission(roleId, permissionIds, lastPermissionIds);
        return ResponseResult.Success(save);
    }


    private void getTreeModelList(List<TreeModel> treeList, List<SysPermission> metaList, TreeModel temp) {
        for (SysPermission permission : metaList) {
            String tempPid = permission.getParentId();
            TreeModel tree = new TreeModel(permission.getId(), tempPid, permission.getName(), permission.getRuleFlag(), permission.isLeaf());
            if (temp == null && StringUtils.isEmpty(tempPid)) {
                treeList.add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            } else if (temp != null && tempPid != null && tempPid.equals(temp.getKey())) {
                temp.getChildren().add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            }
        }
    }


}
